package cn.panda.edu.student;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import cn.panda.edu.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import cn.panda.edu.model.Student;
import cn.panda.edu.util.Constant;
import cn.panda.edu.util.MD5;
import cn.panda.edu.util.ResultDataUtil;

@RestController
@RequestMapping("/api/student")
public class LoginController {

	@Autowired
	private StudentService studentService ;
	@RequestMapping("/login")
	public Map<String , Object> studentLogin(String user, String password, HttpServletRequest request) {
//		String mPass = MD5.encryptPassword(password, user) ;
		Student student = studentService.selectByNameAndPwd(user, password) ;
		if (student != null) {
			request.getSession().setAttribute(Constant.LOGIN_USER, student);
			return ResultDataUtil.resData(200, "登陆成功", student) ;
		} else {
			return ResultDataUtil.resData(500, "账号密码错误！", null);
		}
	}
	
	@RequestMapping("/editPass")
	public Object editPass(String newPass, HttpSession session) {
		Student student = (Student) session.getAttribute(Constant.LOGIN_USER) ;
		String realNewPass = MD5.encryptPassword(newPass, student.getStudentName()) ;
		student.setStudentPassword(realNewPass);
		int k = studentService.updateByPrimaryKey(student) ;
		if (k > 0) {
			return ResultDataUtil.resData(200, "修改成功", null) ;
		} else {
			return ResultDataUtil.resData(500, "修改失败", null) ;
		}
	}
	@RequestMapping("/logout")
	public Object logout(HttpSession session) {
		session.removeAttribute(Constant.LOGIN_USER);
		return ResultDataUtil.resData(200, "退出成功", null) ;
	}
}
